package com.wdm.sms.commonutil.config.inteceptor.springsecurity.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.wdm.sms.commonutil.config.exception.MyException;
import com.wdm.sms.commonutil.config.inteceptor.springsecurity.custom.LoginUserInfoHelper;
import com.wdm.sms.commonutil.enums.ResponseEnum;
import com.wdm.sms.commonutil.utils.jwt.JwtTokenUtils;
import com.wdm.sms.commonutil.utils.jwt.PassToken;
import com.wdm.sms.commonutil.utils.result.ResponseUtil;
import com.wdm.sms.commonutil.utils.result.Result;
import com.wdm.sms.commonutil.utils.result.ResultCodeEnum;
import com.wdm.sms.entity.common.dto.user.token.UserTokenDTO;
import com.wdm.sms.entity.system.SysUser;
import com.wdm.sms.service.redis.RedisService;
import com.wdm.sms.service.user.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import com.wdm.sms.commonutil.jwt.JwtHelper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    private SysUserService sysUserService;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        //如果是登录接口，直接放行
        //"/file".equals(request.getRequestURI().substring(0,5))
        if("/admin/system/index/login".equals(request.getRequestURI()) || "/user/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if(null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.LOGIN_ERROR));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //请求头是否有token
        //String authToken = "Bearer eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJScgwN8dANDXYNUtJRSq0oULIyNLMwNDY1MDc30VFKzy0JycxNBQmaW1qYW5qamBkYAsVLi1OL8hJBEkqJKbmZeUq1AFAmpHBPAAAA.pLU5s3TlrKjUJxxhYS6myuPcFD0aLpM2KndH47O1qnzIqqHDRUDt9WIbMThXBRgA9tx9Xw2Bu3r60cAuZqNNLg";
        String authToken = request.getHeader("token");
        String token;
        if (StringUtils.isNotEmpty(authToken)) {
            token = authToken.substring("Bearer".length() + 1).trim();
        } else{
            token="";
        }
        if(!StringUtils.isEmpty(token)) {
            String username = JwtHelper.getUsername(token);
            if(!StringUtils.isEmpty(username)) {
                //当前用户信息放到ThreadLocal里面
                //LoginUserInfoHelper.setUserId(JwtHelper.getUserId(token));
                LoginUserInfoHelper.setUsername(username);

                //通过username从redis获取权限数据
                String authString = (String)redisTemplate.opsForValue().get(username+"-authority");
                //把redis获取字符串权限数据转换要求集合类型 List<SimpleGrantedAuthority>
                if(!StringUtils.isEmpty(authString)) {
                    List<Map> maplist = JSON.parseArray(authString, Map.class);
                    log.info("用户权限:{}",maplist);
                    List<SimpleGrantedAuthority> authList = new ArrayList<>();
                    for (Map map:maplist) {
                        String authority = (String)map.get("authority");
                        authList.add(new SimpleGrantedAuthority(authority));
                    }
                    return new UsernamePasswordAuthenticationToken(username,null, authList);
                } else {
                    return new UsernamePasswordAuthenticationToken(username,null, new ArrayList<>());
                }
            }
        }
        return null;
    }
}
